using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.ServiceModules
{
    /// <summary>
    /// 模块权限管理器
    /// 负责检查和管理各个模块的启用/禁用权限
    /// </summary>
    public class ModulePermissionManager
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<ModulePermissionManager>? _logger;
        private readonly Dictionary<ModulePermission, bool> _serviceModulePermissions;
        private readonly Dictionary<MiddlewarePermission, bool> _middlewarePermissions;

        public ModulePermissionManager(IConfiguration configuration, ILogger<ModulePermissionManager>? logger = null)
        {
            _configuration = configuration;
            _logger = logger;
            _serviceModulePermissions = new Dictionary<ModulePermission, bool>();
            _middlewarePermissions = new Dictionary<MiddlewarePermission, bool>();
            
            LoadPermissions();
        }

        /// <summary>
        /// 检查服务模块是否有权限启用
        /// </summary>
        /// <param name="permission">模块权限</param>
        /// <returns>是否有权限</returns>
        public bool HasServiceModulePermission(ModulePermission permission)
        {
            // 核心服务始终启用
            if (permission == ModulePermission.CoreServices)
                return true;

            return _serviceModulePermissions.GetValueOrDefault(permission, GetDefaultPermission(permission));
        }

        /// <summary>
        /// 检查中间件模块是否有权限启用
        /// </summary>
        /// <param name="permission">中间件权限</param>
        /// <returns>是否有权限</returns>
        public bool HasMiddlewarePermission(MiddlewarePermission permission)
        {
            // 核心中间件始终启用
            if (permission == MiddlewarePermission.CoreMiddleware)
                return true;

            return _middlewarePermissions.GetValueOrDefault(permission, GetDefaultMiddlewarePermission(permission));
        }

        /// <summary>
        /// 动态设置服务模块权限
        /// </summary>
        /// <param name="permission">模块权限</param>
        /// <param name="enabled">是否启用</param>
        public void SetServiceModulePermission(ModulePermission permission, bool enabled)
        {
            if (permission == ModulePermission.CoreServices)
            {
                _logger?.LogWarning("无法禁用核心服务模块");
                return;
            }

            _serviceModulePermissions[permission] = enabled;
            _logger?.LogInformation($"服务模块 {permission} 权限已设置为: {enabled}");
        }

        /// <summary>
        /// 动态设置中间件权限
        /// </summary>
        /// <param name="permission">中间件权限</param>
        /// <param name="enabled">是否启用</param>
        public void SetMiddlewarePermission(MiddlewarePermission permission, bool enabled)
        {
            if (permission == MiddlewarePermission.CoreMiddleware)
            {
                _logger?.LogWarning("无法禁用核心中间件模块");
                return;
            }

            _middlewarePermissions[permission] = enabled;
            _logger?.LogInformation($"中间件模块 {permission} 权限已设置为: {enabled}");
        }

        /// <summary>
        /// 获取所有模块权限状态
        /// </summary>
        /// <returns>权限状态字典</returns>
        public Dictionary<string, object> GetAllPermissions()
        {
            return new Dictionary<string, object>
            {
                {
                    "ServiceModules",
                    Enum.GetValues<ModulePermission>().ToDictionary(
                        p => p.ToString(),
                        p => HasServiceModulePermission(p)
                    )
                },
                {
                    "MiddlewareModules",
                    Enum.GetValues<MiddlewarePermission>().ToDictionary(
                        p => p.ToString(),
                        p => HasMiddlewarePermission(p)
                    )
                }
            };
        }

        /// <summary>
        /// 从配置加载权限
        /// </summary>
        private void LoadPermissions()
        {
            var moduleConfig = _configuration.GetSection("ModulePermissions");

            // 加载服务模块权限
            var serviceSection = moduleConfig.GetSection("Services");
            foreach (var permission in Enum.GetValues<ModulePermission>())
            {
                if (permission == ModulePermission.CoreServices)
                    continue;

                var configValue = serviceSection.GetValue<bool?>($"{permission}:Enabled");
                if (configValue.HasValue)
                {
                    _serviceModulePermissions[permission] = configValue.Value;
                }
            }

            // 加载中间件权限
            var middlewareSection = moduleConfig.GetSection("Middleware");
            foreach (var permission in Enum.GetValues<MiddlewarePermission>())
            {
                if (permission == MiddlewarePermission.CoreMiddleware)
                    continue;

                var configValue = middlewareSection.GetValue<bool?>($"{permission}:Enabled");
                if (configValue.HasValue)
                {
                    _middlewarePermissions[permission] = configValue.Value;
                }
            }

            _logger?.LogInformation($"已加载 {_serviceModulePermissions.Count} 个服务模块权限和 {_middlewarePermissions.Count} 个中间件权限");
        }

        /// <summary>
        /// 获取默认权限状态
        /// </summary>
        /// <param name="permission">模块权限</param>
        /// <returns>默认权限状态</returns>
        private bool GetDefaultPermission(ModulePermission permission)
        {
            return permission switch
            {
                ModulePermission.LoggingServices => true,           // 日志服务默认启用
                ModulePermission.AuthenticationServices => true,   // 认证默认启用
                ModulePermission.CacheServices => true,            // 缓存默认启用
                ModulePermission.DatabaseServices => true,         // 数据库默认启用
                ModulePermission.PerformanceServices => false,     // 性能优化默认禁用
                ModulePermission.ApplicationServices => true,      // 应用服务默认启用
                ModulePermission.SystemOptimizationServices => false, // 系统优化默认禁用
                ModulePermission.SwaggerServices => false,         // Swagger默认禁用（仅开发环境）
                ModulePermission.AdvancedMonitoringServices => false, // 高级监控默认禁用
                ModulePermission.MultiTenantAdvancedServices => false, // 多租户高级功能默认禁用
                _ => false
            };
        }

        /// <summary>
        /// 获取默认中间件权限状态
        /// </summary>
        /// <param name="permission">中间件权限</param>
        /// <returns>默认权限状态</returns>
        private bool GetDefaultMiddlewarePermission(MiddlewarePermission permission)
        {
            return permission switch
            {
                MiddlewarePermission.PerformanceMiddleware => true,     // 性能中间件默认启用
                MiddlewarePermission.LoggingMiddleware => false,        // 日志中间件默认禁用（仅开发环境）
                MiddlewarePermission.AuthenticationMiddleware => true,  // 认证中间件默认启用
                MiddlewarePermission.RoutingMiddleware => true,         // 路由中间件默认启用
                MiddlewarePermission.SystemOptimizationMiddleware => false, // 系统优化默认禁用
                MiddlewarePermission.SwaggerMiddleware => false,        // Swagger中间件默认禁用
                MiddlewarePermission.SecurityMiddleware => false,       // 安全中间件默认禁用
                _ => false
            };
        }
    }
}
